package edu.seu.mart.controller;

import com.alibaba.fastjson.JSON;

import edu.seu.mart.model.Address;
import edu.seu.mart.model.User;
import edu.seu.mart.model.Goods;
import edu.seu.mart.model.Cart;

import edu.seu.mart.service.*;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/3/12.
 */
@Controller
@RequestMapping("/cart")
public class CartController {

    @Resource
    private IAddressService addressService;

    @Resource
    private ICartService cartService;

    @Resource
    private IGoodsService goodsService;

    String quantity="";
    String[] ids=new String[]{};
    String totalMoney="";
    /**
     * 用户点击添加到购物车，若添加成功则跳转到该页面显示用户刚添加的商品信息
     * 该页面有去购物车结算和返回按钮"/{id}/delete"
     */
    @RequestMapping(value = "/addSuc", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody Message addSuc(@RequestParam("quantity") String quantity, @RequestParam("goodsId") String goodsId,
                         Model model, HttpSession session) throws IOException {
        Message message=new Message();
        User user = (User) session.getAttribute("loginUser");
        Goods goods = goodsService.load(Integer.valueOf(goodsId));
        List<Cart> cartList=cartService.userCartList(user.getId());
        Cart cart1 = new Cart();
        cart1.setQuantity(Integer.valueOf(quantity));
        cart1.setSubtotal(goods.getPrice() * Integer.valueOf(quantity));
        cart1.setGoods(goods);
        cart1.setUser_id(user.getId());
        //判断购物车中是否已存在该商品
        boolean flag=true;
        for(Cart cart:cartList){
            if(cart.getGoods().equals(goods)){
                int num=cart.getQuantity()+Integer.valueOf(quantity);
                if(num<=goods.getStock())
                {
                    cartService.updateCart(cart.getId(),num);
                    flag=false;
                    message.msg="商品已存在！";
                }else {
                    message.msg="您购物车内的该商品数量已达到库存，无法再添加！";
                    flag=false;
                }
            }
        }
        if(flag){
            cartService.add(cart1);
            message.msg="添加成功！";
        }

       message.cart=cartService.getCount(user.getId());
        session.setAttribute("CartCount",message.cart);
       return message;

    }

    /**
     * 显示用户购物车
     */
    @RequestMapping(value = "/userCartList", method = RequestMethod.GET)
    public String userCartList(Model model, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "redirect:/user/login";
        }
        model.addAttribute("cartList", cartService.findUserCart(user.getId()));
        return "user/userCartList";
    }

    /**
     * 删除购物车中的记录
     */
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public String userCartDel(@PathVariable int id) {
        cartService.delete(id);
        return "redirect:/cart/userCartList";
    }

    /**
     * 有选中的删除购物车中的记录
     */
    @RequestMapping(value = "/userCartDelChecked", method = RequestMethod.POST)
    public String userCartDelChecked(@RequestParam("ids") String[] ids) {
        cartService.deleteChecked(ids);
        return "redirect:/cart/userCartList";
    }

    @RequestMapping(value = "/userToPay", method = RequestMethod.POST)
    public String userToPay(@RequestParam("quantity1") String quantity, @RequestParam("ids") String[] ids,
                            @RequestParam("totalMoney") String totalMoney, Model model, HttpSession session) {
        //当前登录的用户
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "redirect:/user/login";
        }
        /**
         * cart1 购物车选中商品栏ID
         */
        this.quantity=quantity;
        this.ids=ids;
        this.totalMoney=totalMoney;
        Integer[] cart1 = new Integer[ids.length];
        for (int i = 0; i < ids.length; i++) {
            cart1[i] = Integer.valueOf(ids[i]);
        }
        /**
         * cart2 购物车所有商品栏和数量
         */
        String[] cart2 = quantity.split(",");
        for (Integer cart : cart1) {
            for (String scart : cart2) {
                String cart3[] = scart.split(":");
                if (Integer.valueOf(cart3[0]).equals(cart)) {
                    cartService.updateCart(Integer.valueOf(cart3[0]), Integer.valueOf(cart3[1]));
                }
            }
        }
        List<Address> addressList = addressService.loadUserAdresss(user.getId());
        if (addressList.isEmpty()) {
            return "redirect:/order/addUserAddress";
        }
        model.addAttribute("addresses", addressList);
        /**
         * 封装前台页面以及订单页面所需json字符串
         */
        Map<Integer, List<Cart>> map = cartService.cartChecked(cart1);
        //按商家ID分的Cart
        List<Map<String, Object>> list = new ArrayList<>();
        for (List<Cart> cartlist : map.values()) {
            Map<String, Object> ordermap = new HashMap<>();
            Cart c = cartlist.get(0);
            ordermap.put("seller_id", c.getGoods().getSeller().getId());
            ordermap.put("seller_name", c.getGoods().getSeller().getName());
            ordermap.put("user_id", c.getUser_id());
            List<Object> item = new ArrayList<>();
            for (Cart cart : cartlist) {
                Map<String, Object> goodsmap = new HashMap<>();
                Goods goods = cart.getGoods();
                goodsmap.put("id", goods.getId());
                goodsmap.put("name", goods.getName());
                goodsmap.put("img", goods.getImage());
                goodsmap.put("quantity", cart.getQuantity());
                goodsmap.put("price", goods.getPrice());
                goodsmap.put("subtotal", cart.getSubtotal());
                goodsmap.put("cartid", cart.getId());
                item.add(goodsmap);
            }
            ordermap.put("goods", item);
            list.add(ordermap);
        }
        String jsoncart = JSON.toJSONString(list);
        System.out.println(jsoncart);
        model.addAttribute("jsoncart", jsoncart);
        model.addAttribute("totalMoney", totalMoney);
        model.addAttribute(new Address());
        return "user/orderVerify";
    }
    @RequestMapping(value = "/userToPay1", method = RequestMethod.POST)
    public String userToPay(@RequestParam("quantity") int quantity, @RequestParam("goodsId") int goodsId
                           , Model model, HttpSession session) {
        //当前登录的用户
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "redirect:/user/login";
        }

        List<Address> addressList = addressService.loadUserAdresss(user.getId());
        if (addressList.isEmpty()) {
            return "redirect:/order/addUserAddress";
        }
        model.addAttribute("addresses", addressList);
        /**
         * 封装前台页面以及订单页面所需json字符串
         */
        Goods goods =goodsService.load(goodsId);
        //按商家ID分的Cart
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> ordermap = new HashMap<>();
        ordermap.put("seller_id", goods.getSeller().getId());
        ordermap.put("seller_name", goods.getSeller().getName());
        ordermap.put("user_id", user.getId());
        Map<String, Object> goodsmap = new HashMap<>();
        goodsmap.put("id", goods.getId());
        goodsmap.put("name", goods.getName());
        goodsmap.put("img", goods.getImage());
        goodsmap.put("quantity", quantity);
        double price = goods.getPrice();
        goodsmap.put("price", price);
        goodsmap.put("subtotal",  price * quantity);
        goodsmap.put("cartid", -1);
        List<Object> item = new ArrayList<>();
        item.add(goodsmap);
        ordermap.put("goods", item);
        list.add(ordermap);
        String jsoncart = JSON.toJSONString(list);
        System.out.println(jsoncart);
        model.addAttribute("jsoncart", jsoncart);
        model.addAttribute("totalMoney", price * quantity);
        model.addAttribute(new Address());
        return "user/orderVerify";
    }

    @RequestMapping(value = "/userToPay", method = RequestMethod.GET)
    public String userToPay1(@RequestParam("quantity1") String quantity, @RequestParam("ids") String[] ids,
                            @RequestParam("totalMoney") String totalMoney, Model model, HttpSession session) {
        //当前登录的用户
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "redirect:/user/login";
        }
        /**
         *
         * cart1 购物车选中商品栏ID
         */
        this.quantity=quantity;
        this.ids=ids;
        this.totalMoney=totalMoney;

        Integer[] cart1 = new Integer[ids.length];
        for (int i = 0; i < ids.length; i++) {
            cart1[i] = Integer.valueOf(ids[i]);
        }
        /**
         * cart2 购物车所有商品栏和数量
         */
        String[] cart2 = quantity.split(",");
        for (Integer cart : cart1) {
            for (String scart : cart2) {
                String cart3[] = scart.split(":");
                if (Integer.valueOf(cart3[0]).equals(cart)) {
                    cartService.updateCart(Integer.valueOf(cart3[0]), Integer.valueOf(cart3[1]));
                }
            }
        }
        List<Address> addressList = addressService.loadUserAdresss(user.getId());
        if (addressList.isEmpty()) {
            return "redirect:/order/addUserAddress";
        }
        model.addAttribute("addresses", addressList);
        /**
         * 封装前台页面以及订单页面所需json字符串
         */
        Map<Integer, List<Cart>> map = cartService.cartChecked(cart1);
        //按商家ID分的Cart
        List<Map<String, Object>> list = new ArrayList<>();
        for (List<Cart> cartlist : map.values()) {
            Map<String, Object> ordermap = new HashMap<>();
            Cart c = cartlist.get(0);
            ordermap.put("seller_id", c.getGoods().getSeller().getId());
            ordermap.put("seller_name", c.getGoods().getSeller().getName());
            ordermap.put("user_id", c.getUser_id());
            List<Object> item = new ArrayList<>();
            for (Cart cart : cartlist) {
                Map<String, Object> goodsmap = new HashMap<>();
                Goods goods = cart.getGoods();
                goodsmap.put("id", goods.getId());
                goodsmap.put("name", goods.getName());
                goodsmap.put("img", goods.getImage());
                goodsmap.put("quantity", cart.getQuantity());
                goodsmap.put("price", goods.getPrice());
                goodsmap.put("subtotal", cart.getSubtotal());
                goodsmap.put("cartid", cart.getId());
                item.add(goodsmap);
            }
            ordermap.put("goods", item);
            list.add(ordermap);
        }
        String jsoncart = JSON.toJSONString(list);
        System.out.println(jsoncart);
        model.addAttribute("jsoncart", jsoncart);
        model.addAttribute("totalMoney", totalMoney);
        model.addAttribute(new Address());
        return "user/orderVerify";
    }


    @RequestMapping(value = "/addUserAddress", method = RequestMethod.POST)
    public String addressAdd(@Validated Address addr, BindingResult br, Model model, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");

        addr.setUser_id(user.getId());
        addressService.add(addr);
        Integer[] cart1 = new Integer[ids.length];
        for (int i = 0; i < ids.length; i++) {
            cart1[i] = Integer.valueOf(ids[i]);
        }
        /**
         * cart2 购物车所有商品栏和数量
         */
        String[] cart2 = quantity.split(",");
        for (Integer cart : cart1) {
            for (String scart : cart2) {
                String cart3[] = scart.split(":");
                if (Integer.valueOf(cart3[0]).equals(cart)) {
                    cartService.updateCart(Integer.valueOf(cart3[0]), Integer.valueOf(cart3[1]));
                }
            }
        }
        List<Address> addressList = addressService.loadUserAdresss(user.getId());
        if (addressList.isEmpty()) {
            return "redirect:/order/addUserAddress";
        }
        model.addAttribute("addresses", addressList);
        /**
         * 封装前台页面以及订单页面所需json字符串
         */
        Map<Integer, List<Cart>> map = cartService.cartChecked(cart1);
        //按商家ID分的Cart
        List<Map<String, Object>> list = new ArrayList<>();
        for (List<Cart> cartlist : map.values()) {
            Map<String, Object> ordermap = new HashMap<>();
            Cart c = cartlist.get(0);
            ordermap.put("seller_id", c.getGoods().getSeller().getId());
            ordermap.put("seller_name", c.getGoods().getSeller().getName());
            ordermap.put("user_id", c.getUser_id());
            List<Object> item = new ArrayList<>();
            for (Cart cart : cartlist) {
                Map<String, Object> goodsmap = new HashMap<>();
                Goods goods = cart.getGoods();
                goodsmap.put("id", goods.getId());
                goodsmap.put("name", goods.getName());
                goodsmap.put("img", goods.getImage());
                goodsmap.put("quantity", cart.getQuantity());
                goodsmap.put("price", goods.getPrice());
                goodsmap.put("subtotal", cart.getSubtotal());
                goodsmap.put("cartid", cart.getId());
                item.add(goodsmap);
            }
            ordermap.put("goods", item);
            list.add(ordermap);
        }
        String jsoncart = JSON.toJSONString(list);
        System.out.println(jsoncart);
        model.addAttribute("jsoncart", jsoncart);
        model.addAttribute("totalMoney", totalMoney);
        model.addAttribute(new Address());
        return "user/orderVerify";


    }
    @RequestMapping(value = "/{id}/deleteAddress", method = RequestMethod.GET)
    public String deleteAddress(@PathVariable int id,Model model, HttpSession session) {
        addressService.delete(id);
        User user = (User) session.getAttribute("loginUser");
        Integer[] cart1 = new Integer[ids.length];
        for (int i = 0; i < ids.length; i++) {
            cart1[i] = Integer.valueOf(ids[i]);
        }
        /**
         * cart2 购物车所有商品栏和数量
         */
        String[] cart2 = quantity.split(",");
        for (Integer cart : cart1) {
            for (String scart : cart2) {
                String cart3[] = scart.split(":");
                if (Integer.valueOf(cart3[0]).equals(cart)) {
                    cartService.updateCart(Integer.valueOf(cart3[0]), Integer.valueOf(cart3[1]));
                }
            }
        }
        List<Address> addressList = addressService.loadUserAdresss(user.getId());
        if (addressList.isEmpty()) {
            return "redirect:/order/addUserAddress";
        }
        model.addAttribute("addresses", addressList);
        /**
         * 封装前台页面以及订单页面所需json字符串
         */
        Map<Integer, List<Cart>> map = cartService.cartChecked(cart1);
        //按商家ID分的Cart
        List<Map<String, Object>> list = new ArrayList<>();
        for (List<Cart> cartlist : map.values()) {
            Map<String, Object> ordermap = new HashMap<>();
            Cart c = cartlist.get(0);
            ordermap.put("seller_id", c.getGoods().getSeller().getId());
            ordermap.put("seller_name", c.getGoods().getSeller().getName());
            ordermap.put("user_id", c.getUser_id());
            List<Object> item = new ArrayList<>();
            for (Cart cart : cartlist) {
                Map<String, Object> goodsmap = new HashMap<>();
                Goods goods = cart.getGoods();
                goodsmap.put("id", goods.getId());
                goodsmap.put("name", goods.getName());
                goodsmap.put("img", goods.getImage());
                goodsmap.put("quantity", cart.getQuantity());
                goodsmap.put("price", goods.getPrice());
                goodsmap.put("subtotal", cart.getSubtotal());
                goodsmap.put("cartid", cart.getId());
                item.add(goodsmap);
            }
            ordermap.put("goods", item);
            list.add(ordermap);
        }
        String jsoncart = JSON.toJSONString(list);
        System.out.println(jsoncart);
        model.addAttribute("jsoncart", jsoncart);
        model.addAttribute("totalMoney", totalMoney);
        model.addAttribute(new Address());
        return "user/orderVerify";
    }
    class  Message{

        public String msg;
        public int cart;
    }
}